
/*
 * 普通收藏 添加或取消
 * @param string product_type 收藏物品类型
 * @param int product_id 收藏物品ID
 * @param string product_title 收藏物品名称
 * @param obj collection_info 收藏物品附加信息
 * @param obj VUEOBJ 实例化的VUE对象
 * */
function updateProductCollection(product_type, product_id, product_title, collection_info, VUEOBJ) {
    var api_host = plus.storage.getItem('HOST_URL');
    mui.ajax({
        url: api_host + '/api/other/other/add_collection',
        data: {
            'product_id': product_id,
            'product_type': product_type,
            'product_title': product_title,
            'collection_info': collection_info
        },
        headers:{'User-Token':plus.storage.getItem('UserToken')},
        timeout:3000,
        dataType: 'json',
        type: 'post',
        success: function (msg) {
            if(msg.code == 1){
                VUEOBJ.collection_status = msg.data.collection_status;
            }else{
                VUEOBJ.collection_status = "NO";
            }
            mui.toast(msg.msg, {duration: '1000',});
        },
        error: function (xhr, type, errorThrown) {
            mui.toast('收藏出错，请重试！', {duration: '2000',});
        }
    });
}

/*
 * 题库题目收藏
 * @param int question_id 题目的ID
 * @param int question_category 题目的类型
 * @param obj VUEOBJ VUE对象
 * */

function questionCollection(question_id, question_category, VUEOBJ) {
    var api_host = plus.storage.getItem('HOST_URL');
    mui.ajax({
        url: api_host + '/api/questionbank/public/add_collection',
        data: {
            'question_id': question_id,
            'category': question_category
        },
        headers:{'User-Token':plus.storage.getItem('UserToken')},
        timeout:3000,
        dataType: 'json',
        type: 'post',
        success: function (msg) {
            VUEOBJ.collection_status = msg.data.collection_status;
            mui.toast(msg.msg, {duration: '1000',});
        },
        error: function (xhr, type, errorThrown) {
            mui.toast('题目收藏失败，请重试！', {duration: '2000',});
        }
    });
}

/*
 *分享方法
 * @param string title 分享出去卡片显示的标题
 * @param string description 分享出去卡片显示的描述信息
 * @param string href 分享出去点击进入的连接
 * @param string thumbs 分享出去显示的小图 小于32K
 */
function globalShare(title,description, href, thumbs) {
    var sweixin = null;
    plus.share.getServices(successCB, errorCB);
    var message = {
        title: title, //分享卡片显示的标题
        content: description,  //分享出去卡片显示的描述信息
        href: href, //分享出去后，点击跳转地址
        thumbs: [thumbs] //分享缩略图
    }
    //调起分享
    plusShare(message, function (res) {
        //分享回调函数
        if (res) {
            plus.nativeUI.toast("分享成功");
        } else {
            plus.nativeUI.toast("分享失败");
        }
    })
}

function successCB(e) {
    console.log(JSON.stringify(e));
}

function errorCB(e) {
    console.log(JSON.stringify(e));
}


//压缩图片
function compressImages(image) {
    console.log("开始压缩");
    let img = image;
    return new Promise((res) => {
        var localPath = plus.io.convertAbsoluteFileSystem(img.replace('file://', ''));
        console.log('after' + localPath);
        // 压缩size
        plus.io.resolveLocalFileSystemURL(localPath, (entry) => {
            entry.file((file) => {// 可通过entry对象操作图片
                console.log("getFile:" + JSON.stringify(file));
                if(file.size > 20480) {// 压缩后size 大于20Kb
                    plus.zip.compressImage({
                        src: img,
                        dst: img.replace('.jpg', '2222.jpg').replace('.JPG', '2222.JPG'),
                        width: '10%',
                        height: '10%',
                        quality: 1,
                        overwrite: true
                    }, (event) => {
                        console.log('success zip****' + event.size);
                        let newImg = img.replace('.jpg', '2222.jpg').replace('.JPG', '2222.JPG');
                        res(newImg);
                    }, function(error) {
                        mui.toast("分享图片太大,需要请重新选择图片!", {duration: '1000',});
                    });
                }
            });
        }, (e) => {
            console.log("Resolve file URL failed: " + e.message);
            mui.toast("分享图片太大,需要请重新选择图片!", {duration: '1000',});
        });
    })
}

//系统加载动画
function showWatting(){
    mui.plusReady(function () {
        plus.nativeUI.showWaiting("",{
            loading:{
                icon:"_www/images/waiting.png", //加载动画地址
                interval:'33',
                height:'80px'
            },
            padding: '0',
            textalign:"center",
            background:"rgba(0,0,0,0)",
        });
    });
}



// 检测网络状态 在网络状态改变时刷新当前页面
function checkNetworkStatus() {
    var connectionStatus = plus.networkinfo.getCurrentType();
    if (connectionStatus < 2) {
        mui.toast('您的设备没有连接到可用的网络', {duration: '2000',});
        return false;
    } else if (connectionStatus == 4) {
        mui.toast('您连接的网络速度较慢，可能需要更长的加载时间', {duration: '2000',});
    }
    document.addEventListener("netchange", function () {
        var network = plus.networkinfo.getCurrentType();
        if (network < 2) {
            mui.toast('您的网络已断开！', {
                duration: '2000',
                
            });
        }
        if (network >= 3) {
            mui.toast('您已经重新连网！', {
                duration: '2000',
                
            });
            var embed = plus.webview.currentWebview();
            embed.reload(true);
        }
    });
}

/*
 * 长按图片保存到本地
 * @param string src 图片的网络地址
 * */
function downImg(src) {
    mui.confirm('保存图片到本地？', '提示', ['保存', '取消'], function (e) {
        if (e.index == 0) {
            var wgtWaiting = plus.nativeUI.showWaiting("保存中...");
            plus.gallery.save(src, function () {
                mui.toast('保存成功', {
                    duration: 2000,
                    
                });
            }, function () {
                mui.toast('保存失败', {
                    duration: 2000,
                    
                })
            });
            wgtWaiting.close();
        } else {
            mui.toast('已取消!', {
                duration: '1000',
                
            });
        }
    })
}

//点击图片预览
//urls Array[ String ]  必选 需要预览的图片地址列表
function openBigPic(urls) {
    plus.nativeUI.previewImage(urls, {
        background:'#ffffff',
    });
}

//使用默认浏览器打开URL
function openDefaultUrl(href) {
    plus.runtime.openURL(href,function () {
        mui.toast('连接打开失败了，请重试...', {
            duration: '1500',
            
        });
    });
}

// 计算对象长度
function countProperties(obj) {
    var count = 0;
    for (var property in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, property)) {
            count++;
        }
    }
    return count;
}

//调用QQ 打开客服聊天界面
function customerService(){
	var api_host = plus.storage.getItem('HOST_URL');
	mui.ajax({
		url: api_host +'/api/user/user/userHasCustomer',
		dataType:'json',
		type:'get',
        headers:{'User-Token':plus.storage.getItem('UserToken')},
        timeout:3000,
		success:function(msg){
			if(msg.code == 1){
			    openMobileQq(msg.data.qq);
			}else{
                openMobileQq(800088966);
			}
		},
		error:function(){
			mui.toast('打开QQ应用失败，请重试...',{duration: '1500', type:'div'});
		}
	})
	
}
//打开手机QQ
function openMobileQq(qq){
    if (plus.os.name == "Android") {
        var main = plus.android.runtimeMainActivity();
        var Intent = plus.android.importClass('android.content.Intent');
        var Uri = plus.android.importClass('android.net.Uri');
        var intent = new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin="+qq));
        main.startActivity(intent);
    }else if(plus.os.name == "iOS"){
        plus.runtime.launchApplication({
            action: "mqq://im/chat?chat_type=wpa&uin="+qq+"&version=1&src_type=web"
        }, function(e) {
            plus.nativeUI.alert("检查到您未安装qq");
        });
    }
}

//打开页面自动弹出软键盘
function open_soft_keyboard(options){
    if(plus.os.name == 'iOS'){
        setTimeout(function(){
            var wv_current = plus.webview.currentWebview().nativeInstanceObject();
            wv_current.plusCallMethod({"setKeyboardDisplayRequiresUserAction":false});
            document.querySelector(options['input']).focus();
        }, 330);
    }else{
        // 因为安卓autofocus只有4.0版本以上才支持，所以这里使用native.js来强制弹出
        setTimeout(function(){
            // 在执行的时候需要让当前webview获取焦点
            var wv_current = plus.android.currentWebview();
            plus.android.importClass(wv_current);
            wv_current.requestFocus();

            var Context = plus.android.importClass("android.content.Context");
            var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
            var main = plus.android.runtimeMainActivity();
            var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0,InputMethodManager.SHOW_FORCED);
            document.querySelector(options['input']).focus();
        }, 50);
    }
}

//返回用户VIP等级等级图标
function getMemberVipImages(num){
    var vip_img = [
        '../../../images/rank_pt.png',
        '../../../images/rank_mg.png',
        '../../../images/rank_by.png',
        '../../../images/rank_hj.png',
        '../../../images/rank_bj.png',
        '../../../images/rank_zs.png'
    ];
    return vip_img[num];
}

//返回用户VIP等级等级图标
function getMemberVipBackgroundImages(num){
   var vip_img = [
        '#929aab',
        '#c06c84',
        '#738598',
        '#957541',
        '#6c5b7b',
        '#3c4f65'
    ];
    return vip_img[num];
}


//返回用户VIP等级名称
function getMemberVipIcon(num) {
    var vip_in = ['普通会员','玫瑰会员','白银会员','黄金会员','白金会员','钻石会员'];
    return vip_in[num];
}


//5+环境下隐藏webview的滚动条。
function hideScrollBar(){
	plus.webview.currentWebview().setStyle({
		scrollIndicator:'none'
	});
}

//点击头部标题返回顶部
function backTop(){
	(function smoothscroll(){
    	var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
	    if (currentScroll > 0) {
	        window.requestAnimationFrame(smoothscroll);
	        window.scrollTo (0,currentScroll - (currentScroll/5));
	    }
	})();
}

//获取当前版本审核状态
function getAudtitStatus(self) {
    var api_host = plus.storage.getItem('HOST_URL');
    var AVCODE = plus.storage.getItem('AVCODE');
    if(mui.os.ios){
        mui.ajax({
            url: api_host+'/api/other/other/checkAppAuditStatus',
            dataType: 'json',
            data: {
                'versionNum': AVCODE,
            },
            type: 'get',
            success: function (msg) {
                console.log(JSON.stringify(msg));
                if(msg.data == 0){
                    self.auditStatus = 'yes';
                }else{
                    self.auditStatus = 'no';
                }
            },
            error: function (xhr, type, errorThrown) {
                console.log(JSON.stringify(xhr));
                console.log(type);
                console.log(errorThrown);
            }
        });
    }else{
        self.auditStatus = 'yes';
    }
}
